package com.example.wudi.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import com.example.wudi.dao.RoleDao;
import com.example.wudi.entity.Role;
import com.example.wudi.params.AddOrUpdateRoleParams;
import com.example.wudi.res.Res;
import com.example.wudi.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role/")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @SaCheckLogin
    @SaCheckPermission("role:select")
    @GetMapping("/findAll")
    @CrossOrigin
    public Res findAll() {
        final List<Role> all = roleService.findAll();
        if(all.size() > 0) {
            return Res.okLit("", all);
        } else {
            return Res.no("获取所有角色失败", null);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("role:select")
    @GetMapping("/findOne")
    @CrossOrigin
    public Res findByRoleId(@RequestParam String id) {
        final RoleDao roleByUserId = roleService.getRoleByUserId(id);
        if(roleByUserId != null) {
            return Res.okBig("", roleByUserId);
        } else {
            return Res.nolit("失败", null);
        }

    }

    @SaCheckLogin
    @SaCheckPermission("role:update")
    @PostMapping("/update")
    @CrossOrigin
    public Res update(@RequestBody AddOrUpdateRoleParams addOrUpdateRoleParams) {
        final int i = roleService.updateRole(addOrUpdateRoleParams);
        if (i>0) {
            return  Res.okLit("修改成功", i);
        } else if(i == -999){
            return Res.noBig("超级管理员不可减少权限", i);
        } else{
            return Res.nolit("更改失败", i);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("role:add")
    @PostMapping("/add")
    @CrossOrigin
    public Res add(@RequestBody AddOrUpdateRoleParams addOrUpdateRoleParams) {
        final int i = roleService.addRole(addOrUpdateRoleParams);
        if (i>0) {
            return  Res.okLit("添加成功", i);
        } else {
            return Res.nolit("添加失败,可能是名字重复了", i);
        }
    }

    @SaCheckLogin
    @SaCheckPermission("role:delete")
    @PostMapping("/delete")
    @CrossOrigin
    public Res delete(@RequestParam String id) {
        final int i = roleService.deleteRole(id);
        if (i>0) {
            return  Res.okLit("删除成功", i);
        } else if(i == -999) {
            return  Res.noBig("超级管理员和无权限人员不可删除，删除后用户角色则会紊乱", i);
        } else {
            return Res.nolit("删除失败", i);
        }

    }
}
